package com.idbk.chargestation.activity.user;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.MainActivity;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.assist.ActivityWelcome;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.app.MyVersion;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonLogin;
import com.idbk.chargestation.bean.JsonUser;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.view.ToastUtil;

/**
 * 登录界面
 *
 * @author lupc, zhx
 */
public class ActivityLogin extends BaseActivity implements OnClickListener,
        OnEditorActionListener {

    private final static String TAG = ActivityLogin.class.getSimpleName();
    private Context mContext;
    private ImageView mImagePassword, mImageBack;
    private EditText mEdtUsername, mEdtPassword;
    private String mUsername, mPassword;
    private boolean mIsPasswordShowFlag;
    private boolean mIsFromWelcomeFlag;
    private int userRole = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        initView();

        mContext = this;

        initData();
    }

    private void initView() {
        initEditText();
        initImageView();
        initOnClickView();
    }

    private void initEditText() {
        mEdtUsername = (EditText) findViewById(R.id.login_username);
        mEdtPassword = (EditText) findViewById(R.id.login_password);
    }

    private void initImageView() {
        mImagePassword = (ImageView) findViewById(R.id.imageview_password_visible);
        mImageBack = (ImageView) findViewById(R.id.toolbar_back);
    }

    @SuppressWarnings("ConstantConditions")
    private void initOnClickView() {
        findViewById(R.id.login).setOnClickListener(this);
        findViewById(R.id.login_forget_password).setOnClickListener(this);
        findViewById(R.id.textview_register).setOnClickListener(this);
        findViewById(R.id.relative_buisuness).setOnClickListener(this);
        mImagePassword.setOnClickListener(this);
        mImageBack.setOnClickListener(this);
        //输入法回车监听
        mEdtUsername.setOnEditorActionListener(this);
        mEdtPassword.setOnEditorActionListener(this);
    }

    private void initData() {
        setFlag();
        setEditTextData();
        setLoginVersionFlag();
    }

    private void setFlag() {
        mIsPasswordShowFlag = false;
        mIsFromWelcomeFlag = false;
    }

    private void setEditTextData() {
        AppContext ac = AppContext.getInstance();
        if (ac.getLoginUserName() != null)
            mEdtUsername.setText(ac.getLoginUserName());
        if (ac.getLoginPassword() != null) {
            mEdtPassword.setText(ac.getLoginPassword());
        }
    }

    private void setLoginVersionFlag() {
        String flag = getIntent().getStringExtra(ActivityWelcome.FIRST_TO_LOGIN);
        if (flag != null && flag.equals(MyVersion.VERSION_NJYX)) {
            mIsFromWelcomeFlag = true;
            mImageBack.setVisibility(View.GONE);
        } else {
            mIsFromWelcomeFlag = false;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.login://登录
                gotoLogin();
                break;
            case R.id.textview_register://注册
                register();
                break;
            case R.id.login_forget_password://忘记密码
                forgetPassword();
                break;
            case R.id.imageview_password_visible:
                setPasswordVisible();
                break;
            case R.id.relative_buisuness:
                buinessLogin();
            default:
                break;
        }
    }

    private void setPasswordVisible() {
        if (mIsPasswordShowFlag) {
            mIsPasswordShowFlag = false;
            mImagePassword.setImageResource(R.drawable.btn_login_password_hidden);
            mEdtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {
            mIsPasswordShowFlag = true;
            mImagePassword.setImageResource(R.drawable.btn_login_password_visible);
            mEdtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
    }

    private void register() {
        Intent intent = new Intent(ActivityLogin.this, ActivityRegister.class);
        startActivityForResult(intent, Const.CODE_REQUEST_REGISTER);
    }

    private void forgetPassword() {
        Intent intent = new Intent(ActivityLogin.this, ActivityForgetPassword.class);
        startActivity(intent);
    }

    private void buinessLogin(){
        Intent intent = new Intent(ActivityLogin.this, ActivityBusinessLogin.class);
        startActivityForResult(intent, Const.CODE_REQUEST_REGISTER);
    }

    private void gotoLogin() {
        if (checkInput()) {
            login();
        }
    }

    private boolean checkInput() {
        mUsername = mEdtUsername.getText().toString();
        mPassword = mEdtPassword.getText().toString();
        if (mUsername.equals("") || (mUsername.length() != 11)) {
            Toast.makeText(this, this.getResources().getString(R.string.tip_please_input_username), Toast.LENGTH_SHORT).show();
            mEdtUsername.setFocusable(true);
            return false;
        }
        if (mPassword.equals("") || mPassword.length() < 6 || mPassword.length() > 20) {
            Toast.makeText(this, this.getResources().getString(R.string.tip_please_input_password), Toast.LENGTH_SHORT).show();
            mEdtPassword.setFocusable(true);
            return false;
        }
        return true;
    }

    private void login() {
        showMyProgressDialog(true, false, "登录中...");
        AppContext ac = AppContext.getInstance();
        mMainRequest = ChargeStationAPI.login(mUsername, mPassword, ac.getPushClientId(), userRole, mResponse);
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEErrorResponse(VolleyError error) {
            Log.e(TAG, error.getMessage(), error.getCause());
            ToastUtil.showToast(mContext, "无法获取服务器数据", Toast.LENGTH_SHORT);
        }

        @Override
        public void onEResponse(String response) {
            JsonLogin result = GsonUtils.toBean(JsonLogin.class, response);
            if (handleResponseStatus(ActivityLogin.this, result)) {
                AppContext.getInstance().saveUserInfo(result.token, mUsername, mPassword, result.outTime, result.userRole);;
                mMainProgressDialog.setMessage("正在拉取用户信息...");
                mMainRequest = ChargeStationAPI.getUserInfo(mResponseUserInfo);
            }
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            dismissMyProgressDialog();
        }
    };

    private final EHttpResponse mResponseUserInfo = new EHttpResponse() {
        @Override
        public void onEResponse(String response) {
            JsonUser result = GsonUtils.toBean(JsonUser.class, response);
            if (handleResponseStatus(ActivityLogin.this, result)) {
                Toast.makeText(mContext, R.string.login_success, Toast.LENGTH_SHORT).show();
                AppContext.getInstance().setUserInfo(result.userId, result.realName);
                setResult(Const.CODE_RESPONSE_LOGIN_SUCCESS);
                firstLogin();
                finish();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Log.e(TAG, error.getMessage(), error.getCause());
            Toast.makeText(mContext, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            dismissMyProgressDialog();
        }
    };

    private void firstLogin() {
        if (mIsFromWelcomeFlag) {
            Intent intent = new Intent(ActivityLogin.this, MainActivity.class);
            startActivity(intent);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断返回码
        if (requestCode == Const.CODE_REQUEST_REGISTER && resultCode == Const.CODE_RESPONSE_REGISTER) {
            setResult(Const.CODE_RESPONSE_LOGIN_SUCCESS);
            firstLogin();
            finish();
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent Event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            InputMethodManager imm = (InputMethodManager) this
                    .getSystemService(Context.INPUT_METHOD_SERVICE);//输入法隐藏
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            gotoLogin();//登录请求
            return true;
        }
        return false;
    }


}
